<template>
  <base-table-layout
    title="育苗价格配置"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.year"
        placeholder="年份"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增配置</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="priceList"
        border
        style="width: 100%"
      >
        <el-table-column prop="year" label="年份" width="120" />
        <el-table-column prop="trayQuantityPerMu" label="每亩票盘数量" width="150" />
        <el-table-column prop="trayUnitPrice" label="票盘单价" width="120" />
        <el-table-column prop="trayFee" label="票盘费" width="120" />
        <el-table-column prop="deliveryFeePerMu" label="每亩配送费" width="120" />
        <el-table-column prop="seedlingCultivationFeePerMu" label="每亩育苗费" width="120" />
        <el-table-column prop="totalFee" label="总费用" width="120" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-form-item label="年份" prop="year">
            <el-input-number v-model="form.year" :min="2000" :max="2100" />
          </el-form-item>
          <el-form-item label="每亩票盘数量" prop="trayQuantityPerMu">
            <el-input-number v-model="form.trayQuantityPerMu" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="票盘单价" prop="trayUnitPrice">
            <el-input-number v-model="form.trayUnitPrice" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="每亩配送费" prop="deliveryFeePerMu">
            <el-input-number v-model="form.deliveryFeePerMu" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="每亩育苗费" prop="seedlingCultivationFeePerMu">
            <el-input-number v-model="form.seedlingCultivationFeePerMu" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入描述信息"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'CultivatePriceManager',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        year: ''
      },
      priceList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isEdit: false,
      currentId: null,
      form: {
        year: new Date().getFullYear(),
        trayQuantityPerMu: 5,
        trayUnitPrice: 5,
        deliveryFeePerMu: 19,
        seedlingCultivationFeePerMu: 89,
        description: ''
      },
      rules: {
        year: [
          { required: true, message: '请输入年份', trigger: 'blur' }
        ],
        trayQuantityPerMu: [
          { required: true, message: '请输入每亩票盘数量', trigger: 'blur' }
        ],
        trayUnitPrice: [
          { required: true, message: '请输入票盘单价', trigger: 'blur' }
        ],
        deliveryFeePerMu: [
          { required: true, message: '请输入每亩配送费', trigger: 'blur' }
        ],
        seedlingCultivationFeePerMu: [
          { required: true, message: '请输入每亩育苗费', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述信息', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑价格配置' : '新增价格配置'
    }
  },
  created() {
    this.fetchPriceList()
  },
  methods: {
    // 获取价格配置列表
    async fetchPriceList() {
      try {
        this.loading = true
        const response = await request.get('/cultivate-prices')
        if (response) {
          this.priceList = response
          this.total = response.length
        }
      } catch (error) {
        console.error('获取价格配置列表失败:', error)
        this.$message.error('获取价格配置列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function() {
      this.currentPage = 1
      await this.fetchPriceList()
    }, 300),

    resetSearch() {
      this.searchForm = {
        year: ''
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchPriceList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchPriceList()
    },

    // 显示新增对话框
    handleAdd() {
      this.isEdit = false
      this.currentId = null
      this.form = {
        year: new Date().getFullYear(),
        trayQuantityPerMu: 5,
        trayUnitPrice: 5,
        deliveryFeePerMu: 19,
        seedlingCultivationFeePerMu: 89,
        description: ''
      }
      this.dialogVisible = true
    },

    // 显示编辑对话框
    handleEdit(row) {
      this.isEdit = true
      this.currentId = row.id
      this.form = {
        year: row.year,
        trayQuantityPerMu: row.trayQuantityPerMu,
        trayUnitPrice: row.trayUnitPrice,
        deliveryFeePerMu: row.deliveryFeePerMu,
        seedlingCultivationFeePerMu: row.seedlingCultivationFeePerMu,
        description: row.description
      }
      this.dialogVisible = true
    },

    // 删除价格配置
    handleDelete(row) {
      this.$confirm('确认删除该价格配置吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await request.delete(`/cultivate-prices/${row.id}`)
          this.$message.success('删除成功')
          this.fetchPriceList()
        } catch (error) {
          console.error('删除价格配置失败:', error)
          this.$message.error('删除价格配置失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        if (this.isEdit) {
          // 编辑价格配置
          await request.put(`/cultivate-prices/${this.currentId}`, this.form)
          this.$message.success('编辑成功')
        } else {
          // 新增价格配置
          await request.post('/cultivate-prices', this.form)
          this.$message.success('添加成功')
        }
        this.dialogVisible = false
        this.fetchPriceList()
      } catch (error) {
        if (error !== false) {
          console.error(this.isEdit ? '编辑价格配置失败:' : '添加价格配置失败:', error)
          this.$message.error(this.isEdit ? '编辑价格配置失败' : '添加价格配置失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.filter-item {
  margin-left: 10px;
}
</style> 